import { defineStore } from 'pinia'
import {
  accountloginRequest,
  getUserInfoById,
  getUserMenuByRoleId
} from '@/service/login/login'
import type { IAccount } from '@/types'
import { loaclCache } from '@/utils/cache'
import router from '@/router'
import { LOGIN_TOKEN } from '@/global/constants'
import { mapMenusToPermissions, mapMenusToRoutes } from '@/utils/mapMenus'
import useMainStore from '../main/main'
import menuConfig from './menuConfig'
interface ILoginState {
  token: string
  userInfo: any
  userMenus: any
  permissions: string[]
}

const useLoginStore = defineStore('login', {
  // 指定state的数据类型
  state: (): ILoginState => ({
    token: loaclCache.getCache(LOGIN_TOKEN) || '',
    userInfo: loaclCache.getCache('userInfo') || {},
    userMenus: loaclCache.getCache('userMenus') || [],
    permissions: []
  }),
  actions: {
    // 账号登录获取用户信息
    async loginAccountAction(account: IAccount) {
      const loginRequest = await accountloginRequest(account)
      const id = loginRequest.data.id
      // const name = loginRequest.data.name
      this.token = loginRequest.data.token
      loaclCache.setCache(LOGIN_TOKEN, this.token)
      // 获取用户的详细信息
      const userInfoResult = await getUserInfoById(id)
      this.userInfo = userInfoResult.data
      // 根据角色获取用户权限
      const userMenusResult = await getUserMenuByRoleId(this.userInfo.id)
      this.userMenus = this.getAll(userMenusResult.data)

      // 本地缓存
      loaclCache.setCache('userInfo', this.userInfo)
      loaclCache.setCache('userMenus', this.userMenus)

      // 请求角色/部门所有数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()

      // 获取登录用户的所有按钮权限
      const permissions = mapMenusToPermissions(this.userMenus)
      this.permissions = permissions
      // 动态添加路由
      const routes = mapMenusToRoutes(this.userMenus)
      routes.forEach((route) => router.addRoute('main', route))
      // 页面跳转(main页面)
      router.push('/main')
    },
    loadLocalCacheAction() {
      // 1.用户进行刷新默认加载数据
      const token = loaclCache.getCache(LOGIN_TOKEN)
      const userInfo = loaclCache.getCache('userInfo')
      const userMenus = loaclCache.getCache('userMenus')
      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus
        // 请求角色/部门所有数据
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()
        // 获取登录用户的所有按钮权限
        const permissions = mapMenusToPermissions(this.userMenus)
        this.permissions = permissions
        // 2.动态添加路由
        const routes = mapMenusToRoutes(this.userMenus)
        routes.forEach((route) => router.addRoute('main', route))
      }
    },
    // 获取所有菜单
    getAll(userMenus: any[]) {
      return [...userMenus, ...menuConfig]
    }
  }
})

export default useLoginStore
